import { useEffect, useState } from 'react'
import { Modal, Form, Input, Select, Message } from '@arco-design/web-react'
import { createPipeline, updatePipeline } from '@/api/pipeline'
import { getWorkflows } from '@/api/workflow'
import type { Pipeline, WorkflowDefinition } from '@/types'

const FormItem = Form.Item
const Option = Select.Option

interface PipelineFormModalProps {
  visible: boolean
  pipeline?: Pipeline | null
  onCancel: () => void
  onSuccess: () => void
}

export default function PipelineFormModal({
  visible,
  pipeline,
  onCancel,
  onSuccess,
}: PipelineFormModalProps) {
  const [form] = Form.useForm()
  const [workflows, setWorkflows] = useState<WorkflowDefinition[]>([])
  const [loading, setLoading] = useState(false)
  const isEdit = !!pipeline

  // 加载工作流列表
  useEffect(() => {
    if (visible) {
      loadWorkflows()
    }
  }, [visible])

  const loadWorkflows = async () => {
    try {
      const data = await getWorkflows()
      setWorkflows(data.filter((w) => w.isEnabled))
    } catch (error) {
      console.error('Failed to load workflows:', error)
    }
  }

  useEffect(() => {
    if (visible && pipeline) {
      form.setFieldsValue({
        name: pipeline.name,
        description: pipeline.description,
        workflowDefinitionId: pipeline.workflowDefinitionId,
        repositoryUrl: pipeline.repositoryUrl,
        branch: pipeline.branch,
      })
    } else if (visible) {
      form.resetFields()
    }
  }, [visible, pipeline, form])

  const handleSubmit = async () => {
    try {
      const values = await form.validate()
      setLoading(true)

      if (isEdit && pipeline) {
        await updatePipeline(pipeline.id, values)
        Message.success('流水线更新成功')
      } else {
        await createPipeline(values)
        Message.success('流水线创建成功')
      }

      form.resetFields()
      onSuccess()
    } catch (error) {
      console.error('Failed to save pipeline:', error)
    } finally {
      setLoading(false)
    }
  }

  return (
    <Modal
      title={isEdit ? '编辑流水线' : '创建流水线'}
      visible={visible}
      onOk={handleSubmit}
      onCancel={() => {
        form.resetFields()
        onCancel()
      }}
      confirmLoading={loading}
      autoFocus={false}
      focusLock={true}
      okText="确定"
      cancelText="取消"
    >
      <Form form={form} layout="vertical" autoComplete="off">
        <FormItem
          label="流水线名称"
          field="name"
          rules={[
            { required: true, message: '请输入流水线名称' },
            { minLength: 2, message: '名称至少2个字符' },
            { maxLength: 50, message: '名称最多50个字符' },
          ]}
        >
          <Input placeholder="请输入流水线名称" />
        </FormItem>

        <FormItem
          label="描述"
          field="description"
          rules={[{ maxLength: 200, message: '描述最多200个字符' }]}
        >
          <Input.TextArea
            placeholder="请输入流水线描述"
            rows={3}
            showWordLimit
            maxLength={200}
          />
        </FormItem>

        <FormItem
          label="关联工作流"
          field="workflowDefinitionId"
          rules={[{ required: true, message: '请选择工作流' }]}
        >
          <Select placeholder="请选择工作流" allowClear>
            {workflows.map((workflow) => (
              <Option key={workflow.id} value={workflow.id}>
                {workflow.name} (v{workflow.version})
              </Option>
            ))}
          </Select>
        </FormItem>

        <FormItem
          label="仓库地址"
          field="repositoryUrl"
          rules={[
            { required: true, message: '请输入仓库地址' },
            {
              match: /^https?:\/\/.+/,
              message: '请输入有效的 Git 仓库地址',
            },
          ]}
        >
          <Input placeholder="https://github.com/user/repo.git" />
        </FormItem>

        <FormItem
          label="分支"
          field="branch"
          rules={[{ required: true, message: '请输入分支名称' }]}
          initialValue="main"
        >
          <Input placeholder="main" />
        </FormItem>
      </Form>
    </Modal>
  )
}
